import CryptoJS from 'crypto-js'
import JSEncrypt from 'jsencrypt'

const parse = CryptoJS.enc.Latin1.parse

function randString(length = 16) {
  let str = ''
  while (str.length < length) {
    str += Math.random().toString(36).substr(2)
  }
  return str.substr(0, length)
}

export function hash(input) {
  return CryptoJS.SHA256(input).toString()
}

export function aesEncrypt(origin, key, iv) {
  const config = {
    iv: parse(iv),
    mode: CryptoJS.mode.CBC
  }
  const encrypted = CryptoJS.AES.encrypt(origin, parse(key), config)
  return encrypted.toString()
}

export function aesDecrypt(encrypted, key, iv) {
  const config = {
    iv: parse(iv),
    mode: CryptoJS.mode.CBC
  }
  const decrypted = CryptoJS.AES.decrypt(encrypted, parse(key), config)
  return decrypted.toString(CryptoJS.enc.Utf8)
}

export function rsaEncrypt(publickey, input) {
  const encrypter = new JSEncrypt()
  encrypter.setPublicKey(publickey)
  return encrypter.encrypt(input)
}

/**
 * 将原密码加密为加密后的密码、enkey和iv
 * @param {string} password 公钥
 * @param {string} password 原密码
 */
export function encryptPassword(publickey, password) {
  const key = randString(16)
  const iv = randString(16)
  const enkey = rsaEncrypt(publickey, key)
  const enpassword = aesEncrypt(password, key, iv)
  return {
    password: enpassword,
    enkey,
    iv
  }
}
